import React, { useState, useEffect } from 'react';
import s from './style.module.css';
import cn from 'classnames';
import moment from 'moment';
import Breadcrumb, { Item } from '../../../../../../components/Breadcrumb';
import Label from '../../../../../../components/Label';
import Anchor from '@knownsec/react-component/dist/Anchor';
import Table from '@knownsec/react-component/dist/Table';
import ReactDiffViewer, { DiffMethod } from 'react-diff-viewer';
import { withRouter } from 'react-router';
import PropTypes from 'prop-types';
import { datetime } from '../../../../../../../common/formatter';
import fetchFer from 'API/fetch';
import AddYunaqBlacklist from '../../../../../../components/AddYunaqBlacklist';
import { WARNING_CATEGORY_KEY_LABEL_MAP } from '../../../../../../../common/constants';
import {
	turnToUrlparam,
	GetQueryString,
} from '../../../../../../helpers/getUrlParams';
import Loading from '@knownsec/react-component/dist/Loading';
import { CaretRightOutlined } from '@ant-design/icons';
import { Collapse } from 'antd';
const { Panel } = Collapse;

const { Link } = Anchor;
const reasonMap = {
	1: '暂不关注',
	2: '误报',
	3: '其他'
}

const filterChangeType = [
	{ label: '结构变更', value: 'structure' },
	{ label: '文本变更', value: 'text' },
	{ label: '资源变更', value: 'resource' },
]

function WebChangeCheckDetail({ location }) {
	const [loading, setLoading] = useState(false);

	let locationInfo = {};
	if (location?.state) {
		sessionStorage.setItem('locationState', JSON.stringify(location.state));
		locationInfo = location?.state;
	} else {
		const state = JSON.parse(sessionStorage.locationState);
		locationInfo = state;
	}
	const { atid, id, warningId, isHistory, taskType, warning_id } = locationInfo;

	const handleAnchorClick = e => {
		e.preventDefault();
	};
	const [row, setRow] = useState(null);
	const getRow = async () => {
		setLoading(true);
		const isIgnore = location.pathname.includes('/policy-manage/ignore-risk-detail')
		const sendData = { id, warningId, warning_id };
		const params = turnToUrlparam(sendData);
		const url = isIgnore ? '/api/v2/tasks/warning/ignore' : '/api/v2/tasks/changeCheck/evidence'
		const res = await fetchFer(`${url}?${params}`, {
			method: 'GET',
		});
		if (res.code === 200) {
			if (isIgnore) {
				const data_ = JSON.parse(JSON.stringify(res.data) || null) || {}
				delete data_.detail
				setRow({...res.data.detail, ...data_, isIgnore});
			} else {
				setRow(res.results);
			}
		}
		setLoading(false);
	};
	useEffect(() => {
		getRow();
	}, []);
	const cJoin = e => {
		return e ? (e.length ? e.join('｜') : '暂无') : '暂无';
	};

	const formatChangeTypes = (detail) => {
		if (!detail) {
			return "暂无"
		}
		let types = []
		for (const detailKey in detail) {
			types.push(WARNING_CATEGORY_KEY_LABEL_MAP.changeCheck[detailKey].substring(0,2))
		}
		return types.join("、") + "变更"
	}
	const formatSize = (size) => {
		if (!size) {
			return '--'
		}
		return (size / 1024).toFixed(3) + "KB"
	}

	const getStatus = (change) => {
		let status = '- -';
		if (change.baseline?.md5 && change.current?.md5) {
			status = '变化';
		} else if (change.baseline?.md5 && !change.current?.md5) {
			status = '删除';
		} else if (!change.baseline?.md5 && !change.current?.md5) {
			status = '新增';
		}
		return status
	};

	const bread = () => {
		if (location.pathname.includes('/asset-manage/manage/web')) {
			return (
				<Breadcrumb>
					<Item disabled key="asset-manage">
						资产管理
					</Item>
					<Item key="manage/web">Web资产</Item>
					<Item key="Detail">详情</Item>
					<Item>篡改详情</Item>
				</Breadcrumb>
			);
		} else if (location.pathname.includes('/policy-manage/ignore-risk-detail')) {
			return <Breadcrumb>
				<Item disabled key="policy-manage">
					综合管理
				</Item>
				<Item key="ignore-risk-manage">已忽略威胁</Item>
				<Item>威胁详情</Item>
			</Breadcrumb>
		} else {
			return (
				<Breadcrumb>
					<Item disabled key="job-manage">
						任务管理
					</Item>
					<Item key="web-task">Web安全监测</Item>
					<Item key={`detail?id=${atid}&type=${taskType}&tag=vul`}>
						监测结果
					</Item>
					{isHistory && (
						<Item
							key={`history?asset_task_id=${atid}&task_id=${id}&task_types=vul`}
						>
							历史任务
						</Item>
					)}
					<Item>篡改详情</Item>
				</Breadcrumb>
			);
		}
	};
	return (
		<div className={s.vulDetail}>
			<div className={s.breadcrumb}>{bread()}</div>
			<Loading show={loading} label="" />
			<div className={s.container}>
				<div>
					<div className={s.header}>
						<Label className={cn(s.mb10, s.mt20)}>威胁详情</Label>
					</div>
					<div className={cn(s.df, s.aic, s.p0_10)}>
						<span className={s.flex1}>变更类型：{formatChangeTypes(row?.detail)}</span>
						<span className={s.flex1}>威胁等级：{row?.levelName}</span>
						<span className={s.flex1}>
							发现时间：{datetime(row?.foundAt) || '暂无'}
						</span>
					</div>
					{row?.isIgnore && <div className={cn(s.df, s.aic, s.p0_10, s.mt10)}>
						<span className={s.flex1}>
							忽略时间：{datetime(row?.ignored_time) || '暂无'}
						</span>
						<span className={'flex2'}>忽略原因：{reasonMap[row?.reason?.type]}</span>
					</div>}
				</div>
				<div className={cn(s.df, s.aifs, s.pr, s.mt24, s.flex1, s.vdBox)}>
					<Anchor
						className={s.anchoritem}
						onClick={handleAnchorClick}
						getContainer={() => document.getElementById('vd')}
					>
						<Link href="#query-content" title="风险地址" />
						{row?.detail?.text && <Link href="#response-content" title="文本变更" />}
						{row?.detail?.structure && <Link href="#payload" title="结构变更" />}
						{row?.detail?.resource && <Link href="#vul-detail" title="资源变更" />}
					</Anchor>
					<div id="vd" className={cn(s.vd, s.p0_10)}>
						<div id="query-content">
							<Label className={cn(s.mb10, s.mt20)}>风险地址</Label>
							<div className={s.p0_5}>{row?.affects}</div>
						</div>
						{row?.detail?.text && <div id="response-content">
							<Label className={cn(s.mb10, s.mt20)}>文本变更</Label>
							<div className={s.p0_5}>
								<div className='df aic mb10 jcsb'>
									<div>变更比例：{(row.detail.text.change_ratio * 100).toFixed(2)}%</div>
									<div className='df aic'>
										<div className={cn(s.delBg, 'tac w80 mr20')}>删除部分</div>
										<div className={cn(s.addBg, 'tac w80')}>新增部分</div>
									</div>
								</div>
								<ReactDiffViewer
                  styles={{
                    line: { 'word-break': ' break-all' },
                  }}
									leftTitle={<div className='df aic'>
										<div className={'w50 mr20'}>行号</div>
										<div>样本内容</div>
									</div>}
									rightTitle={<div className='df aic'>
										<div className={'w50 mr20'}>行号</div>
										<div>变更后内容</div>
									</div>}
									oldValue={row.detail.text.change.baseline?.content || ""}
									newValue={row.detail.text.change.current?.content || ""}
                  compareMethod={DiffMethod.WORDS}
                  splitView={true}
                  showDiffOnly={false}
                />
								<div className='mb10 mt10'>基本信息对比</div>
								<Table className={s.rowSpanTable} columns={[
									{ key: 'name', dataIndex: 'name', title: '属性' },
									{ key: 'change0', dataIndex: 'change0', title: '样本文件' },
									{ key: 'change1', dataIndex: 'change1', title: '变更后文件' },
								]} data={[
									{ name: 'MD5', change0: row.detail.text.change.baseline?.md5, change1: row.detail.text.change.current?.md5 },
									{ name: '文件大小', change0: formatSize(row.detail.text.change.baseline?.size), change1: formatSize(row.detail.text.change.current?.size) },
									{ name: '状态码', change0: row.detail.text.change.baseline?.status_code, change1: row.detail.text.change.current?.status_code },
								]} />
							</div>
						</div>}
						{row?.detail?.structure && <div id="payload">
							<Label className={cn(s.mb10, s.mt20)}>结构变更</Label>
							<div className={s.p0_5}>
								<div className='df aic mb10 jcsb'>
									<div>变更比例：{(row.detail.structure.change_ratio * 100).toFixed(2)}%</div>
									<div className='df aic'>
										<div className={cn(s.delBg, 'tac w80 mr20')}>删除部分</div>
										<div className={cn(s.addBg, 'tac w80')}>新增部分</div>
									</div>
								</div>
								<ReactDiffViewer
                  styles={{
                    line: { 'word-break': ' break-all' },
                  }}
									leftTitle={<div className='df aic'>
										<div className={'w50 mr20'}>行号</div>
										<div>样本代码</div>
									</div>}
									rightTitle={<div className='df aic'>
										<div className={'w50 mr20'}>行号</div>
										<div>变更后代码</div>
									</div>}
                  oldValue={row.detail.structure.change.baseline?.content || ""}
                  newValue={row.detail.structure.change.current?.content || ""}
                  compareMethod={DiffMethod.WORDS}
                  splitView={true}
                  showDiffOnly={false}
                />
								<div className='mb10 mt10'>基本信息对比</div>
								<Table className={s.rowSpanTable} columns={[
									{ key: 'name', dataIndex: 'name', title: '属性' },
									{ key: 'change0', dataIndex: 'change0', title: '样本文件' },
									{ key: 'change1', dataIndex: 'change1', title: '变更后文件' },
								]} data={[
									{ name: 'MD5', change0: row.detail.structure.change.baseline?.md5, change1: row.detail.structure.change.current?.md5 },
									{ name: '文件大小', change0: formatSize(row.detail.structure.change.baseline?.size), change1: formatSize(row.detail.structure.change.current?.size) },
									{ name: '状态码', change0: row.detail.structure.change.baseline?.status_code, change1: row.detail.structure.change.current?.status_code },
								]} />
							</div>
						</div>}
						{row?.detail?.resource &&
							<div id="vul-detail">
								<Label className={cn(s.mb10, s.mt20)}>资源变更</Label>
								<div className={s.p0_5}>
									<span>变更比例：{(row.detail.resource.change_ratio * 100).toFixed(2)}%</span>
									<span className={s.resourceChange}>样本资源共<span className={s.resourceChangeCount}>{row.detail.resource.baseline_resource_count}</span>个，本次检测对比样本存在变更资源数<span className={s.resourceChangeCount}>{row.detail.resource.change_count}</span>个。</span>
								</div>
								<div>
									{row.detail.resource.changes.map((change) => {
										return (
											<Collapse
											defaultActiveKey={[change["url"]]}
											className={s.collapse}
											expandIconPosition="right"
											expandIcon={({isActive}) => (
												<CaretRightOutlined
													style={{color: '#ccc'}}
													rotate={isActive ? 270 : 90}
												/>
											)}
											>
												<Panel
													forceRender={true}
													header={[change["url"]]}
													key={[change["url"]]}
												>
													<Table pro style={{minHeight: "141px"}} className={s.rowSpanTable} columns={[
														{key: 'name', dataIndex: 'name', title: '属性'},
														{key: 'change0', dataIndex: 'change0', title: '样本文件'},
														{key: 'change1', dataIndex: 'change1', title: '变更后文件'},
														{key: 'status', dataIndex: 'status', title: '状态', onCell: (i, index) => {
																if (index === 0) {
																	return { rowSpan: 2 }
																}
																if (index === 1) {
																	return { rowSpan: 0 }
																}
																return {}
															}},
													]} data={[
														{
															name: 'MD5',
															change0: change.baseline?.md5 || "- -",
															change1: change.current?.md5 || "- -",
															status: getStatus(change)
														},
														{
															name: '文件大小',
															change0: formatSize(change.baseline?.size),
															change1: formatSize(change.current?.size),
															status: getStatus(change)
														},
													]}/>
												</Panel>
											</Collapse>
										)})}
								</div>
							</div>
						}
					</div>
				</div>
			</div>
		</div>
	);
}

WebChangeCheckDetail.propTypes = {
	location: PropTypes.any,
};
export default withRouter(WebChangeCheckDetail);
